{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "b9a883fe-087b-462a-8a84-9e50315796de",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "最后留下的是原来第4号的那位。\n"
     ]
    }
   ],
   "source": [
    "def josephus(n, k):\n",
    "    # 初始化最后留下的人的编号为0（因为我们要从1开始计数，所以最后要加1）\n",
    "    # 这里用0开始是为了方便计算，最后结果+1即可\n",
    "    last_person = 0\n",
    "    # 从1开始，因为我们要模拟第一个人\n",
    "    for i in range(1, n + 1):\n",
    "        # 每报到k的人就“退出”，但实际上是更新last_person的值\n",
    "        last_person = (last_person + k) % i\n",
    "    # 因为我们从0开始计数，所以最后要加1\n",
    "    return last_person + 1\n",
    "\n",
    "# 示例：n个人，报到3的人退出\n",
    "n = 10  # 可以改变这个值来测试不同的n\n",
    "k = 3   # 报数的上限\n",
    "print(f\"最后留下的是原来第{josephus(n, k)}号的那位。\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "26bf1938-0d58-4e29-bc46-1bdd21f139a7",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
